package com.example.nftapp.http;

import android.util.Log;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * 网络请求工具类
 */
public class HttpUtil {

    /**
     * 通用GET方法
     *
     * @param urlStr   接口地址
     * @param callback 成功后的回调
     */
    public static void doGet(String urlStr, HttpCallback callback) {
        new Thread(() -> {
            try {
                // 创建URL对象
                URL url = new URL(urlStr);
                // 客户端-服务器端 建立通信桥梁
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                // 设置请求方法为GET方法
                connection.setRequestMethod("GET");
                // 设置字符集，解决中文乱码问题
                connection.setRequestProperty("Charset", "UTF-8");
                // 进行连接
                connection.connect();
                int responseCode = connection.getResponseCode();
                if (responseCode == 200) {
                    // 请求成功，则读取服务器返回的数据
                    HttpResponse httpResponse = readData(connection);
                    if (httpResponse.getErrorCode() != 0) {
                        //出错了
                        Log.e("HTTP_ERROR", httpResponse.getErrorMsg());
                    } else {
                        // 正常，调用回调接口，传入HttpResponse
                        callback.onHttpSucceed(httpResponse);
                    }
                } else {
                    // 请求失败
                    Log.e("ERROR", "请求失败，错误码：" + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 通用POST方法
     *
     * @param postUrl   url地址
     * @param paramters 参数键值对
     * @param callback  回调
     */
    public static void doPost(String postUrl, HashMap<String, String> paramters, HttpCallback callback) {
        // 通过新起一个线程来执行网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 创建URL对象
                    URL url = new URL(postUrl);
                    // 打开连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    // 设置请求的方法为POST/GET
                    connection.setRequestMethod("POST");
                    // 设置请求头
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    // 构建 POST 请求参数
                    StringBuilder postData = new StringBuilder();
                    paramters.entrySet().forEach(new Consumer<Map.Entry<String, String>>() {
                        @Override
                        public void accept(Map.Entry<String, String> entry) {
                            postData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                        }
                    });
                    String params = postData.substring(0, postData.length() - 1);
                    // 发送参数给服务器
                    connection.getOutputStream().write(params.getBytes(StandardCharsets.UTF_8));
                    // 连接，获取服务器返回的响应数据
                    connection.connect();
                    int responseCode = connection.getResponseCode();
                    if (responseCode == 200) {
                        // 请求成功，则读取服务器返回的数据
                        HttpResponse httpResponse = readData(connection);
                        if (httpResponse.getErrorCode() != 0) {
                            //出错了
                            Log.e("HTTP_ERROR", httpResponse.getErrorMsg());
                        } else {
                            // 正常，调用回调接口，传入HttpResponse
                            callback.onHttpSucceed(httpResponse);
                        }
                    } else {
                        // 请求失败
                        Log.e("ERROR", "请求失败，错误码：" + responseCode);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 读取数据，返回HttpResponse
     *
     * @param connection
     * @return
     * @throws IOException
     */
    private static HttpResponse readData(HttpURLConnection connection) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
        // StringBuilder 拼接读取的结果
        StringBuilder response = new StringBuilder();
        // while循环，一次读取一行
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        Gson gson = new Gson();
        return gson.fromJson(response.toString(), HttpResponse.class);
    }

}
